/*
 * iirfilter.cpp
 *
 *  Created on: Dec 11, 2012
 *      Author: mark
 */

#define		sizeofarray(array)		(sizeof(array) / (sizeof(array[0])))

#include "iirfilter.h"

IIRFilter::IIRFilter(double bCoef[], double aCoef[]) {
	// Prepare
	a = aCoef;
	b = bCoef;
	y = new double[sizeofarray(a)];
	x = new double[sizeofarray(b)];

	// Normalise numerator coefficients
	for (unsigned int i = 0; i < sizeofarray(b); i++) {
		b[i] = bCoef[i] / aCoef[0];
	}

	// Normalise denominator coefficients
	for (unsigned int i = 0; i < sizeofarray(a); i++) {
		a[i] = aCoef[i] / aCoef[0];
	}
}

IIRFilter::~IIRFilter() {
	// Clear memory
	delete a;
	delete b;
	delete x;
	delete y;
}

double IIRFilter::step(double input) {
	// Initialise running sum output
	double output = 0;
	for (int i = sizeofarray(x) - 1; i > 0; i--) {
		x[i] = x[i - 1];
		output += b[i] * x[i];
	}
	x[0] = input;
	output += b[0] * x[0];

	for (int i = sizeofarray(y) - 1; i > 0; i--) {
		y[i] = y[i-1];
		output -= a[i] * y[i];
	}
	y[0] = output;

	return output;
}















